<template>
  <div>
    <a-card>
      <div ref="lineChart1" :style="{width:'100%',height:'368px'}"></div>
      <div ref="lineChart2" :style="{width:'100%',height:'368px'}"></div>
      <div ref="lineChart3" :style="{width:'100%',height:'368px'}"></div>
      <div ref="lineChart4" :style="{width:'100%',height:'368px'}"></div>
      <div ref="lineChart5" :style="{width:'100%',height:'368px'}"></div>
    </a-card>
  </div>
</template>
<script>

import { getAction } from '@/api/manage'
export default
{
  name: 'sport',
  data() {
    return {
      url: {
        list: 'health/skSportRecord/getSprotStatistical',
        allList: 'health/skSportRecord/getAvgSprotStatistical',
        stuList: 'health/skSportRecord/getStudentSprotStatistical'
      },
      searchData: {
        semesterId: '',
        classId: '',
        studentId: '',
        startDate: '',
        endDate: ''
      },
      color:["#0CDF8A","#3EACE5"],
      dataList:[],
      allList:[],
      outList:[],
      numList:[]
    }
  },
  props:["dataForm","monthName","className"],
  components: {},
  filters: {},
  
  computed: {},
  
  created() {
  },
  
  activated() {
  },

  mounted() {
    this.load()
  },

  methods: {
    load() {
      const dataForm = this.dataForm
      this.numList = []
      // 查询列表数据
      this.searchData.semesterId = dataForm.semesterId ? dataForm.semesterId : dataForm.semesterHistoryId
      this.searchData.classId = dataForm.classId ? dataForm.classId : undefined
      this.searchData.studentId = dataForm.studentId ? dataForm.studentId : undefined
      this.searchData.startDate = dataForm.startDate;
      this.searchData.endDate = dataForm.endDate;
      if(dataForm.studentId) {
        this.initStudentChart()
      }else if(dataForm.classId) {
        this.initClassChart();
      }else{
        this.initAllChart();
      }
    },
    // 全园
    initAllChart() {
      //全部
      this.all();
      //户外
      this.out();
      //对比统计
      this.compare();
      // setTimeout(() => {
      //   this.initMutiLineChart(this.$refs.lineChart5, '学期月平均各项运动对比统计', categorys, xDataList);
      // }, 500);
    },
    // 单个班级
    initClassChart() {
      //全部
      this.all();
      //户外
      this.out();
      //对比统计
      this.compare();
    },
    // 单个幼儿
    initStudentChart() {
      this.student();
    },
    all() {
      // 查询运动数据
      const params = {
        statisticalScope: 'all',
        timeScope: this.searchData.semesterId,
        classId: this.searchData.classId,
        startDate: this.searchData.startDate,
        endDate: this.searchData.endDate
      }
      getAction(this.url.list, params).then(res => {
        if(res.success) {
          this.allList = res.result;
          
          //全园月平均
          var categorys = [];
          var xData1 = [];
          var xData2 = [];
          var xData = [];
          const daysColums = this.dataForm.daysColums;
          for(let rowIndex = 0; rowIndex < daysColums.length; rowIndex++){
            const rowString = daysColums[rowIndex].toString();
            categorys.push(rowString.substring(8));
            const dayData = res.result.find(item => item.statisticalDate == rowString);
            if (dayData){
              xData1.push(dayData.avgAmount.toFixed(2));
              xData2.push(dayData.avgStepNumber.toFixed(2));
              xData.push(dayData.avgDuration.toFixed(2));
            } else {
              xData1.push(0);
              xData2.push(0);
              xData.push(0);
            }
          }
          this.initDoubleLineChart(this.$refs.lineChart1, '日平均全天运动量/步数统计', categorys, xData1, xData2);
          
          this.initLineChart(this.$refs.lineChart2, '日平均全天运动时长统计', categorys, xData);
        }
      })
    },
    out() {
      // 查询运动数据
      const params = {
        areaType: '1',
        statisticalScope: 'all',
        timeScope: this.searchData.semesterId,
        classId: this.searchData.classId,
        startDate: this.searchData.startDate,
        endDate: this.searchData.endDate
      }
      getAction(this.url.list, params).then(res => {
        if(res.success) {
          this.outList = res.result;
          
          //全园月平均
          var categorys = [];
          var xData1 = [];
          var xData2 = [];
          var xData = [];
          const daysColums = this.dataForm.daysColums;
          for(let rowIndex = 0; rowIndex < daysColums.length; rowIndex++){
            const rowString = daysColums[rowIndex].toString();
            categorys.push(rowString.substring(8));
            const dayData = res.result.find(item => item.statisticalDate == rowString);
            if (dayData){
              xData1.push(dayData.avgAmount.toFixed(2));
              xData2.push(dayData.avgStepNumber.toFixed(2));
              xData.push(dayData.avgDuration.toFixed(2));
            } else {
              xData1.push(0);
              xData2.push(0);
              xData.push(0);
            }
          }
          this.initDoubleLineChart(this.$refs.lineChart3, '日平均户外运动量/步数统计', categorys, xData1, xData2);
          
          //户外和室内做对比
          this.initLineChart(this.$refs.lineChart4, '日平均户外运动时长统计', categorys, xData);
        }
      })
    },
    compare() {
      // 查询运动数据
      const params = {
        statisticalScope: this.searchData.classId ? 'student' : 'class',
        semesterId: this.searchData.semesterId,
        classId: this.searchData.classId,
        startDate: this.searchData.startDate,
        endDate: this.searchData.endDate
      }
      getAction(this.url.allList, params).then(res => {
        if(res.success) {
          //全园月平均
          var categorys = [];
          var xDataList = [
            [],[],[],[],[],[]
          ];
          res.result.forEach(data => {
            categorys.push(params.statisticalScope == 'class' ? data.className : data.studentName);

            // 户外
            xDataList[0].push(data.avgDuration.toFixed(2));
            xDataList[1].push(data.avgAmount.toFixed(2));
            xDataList[2].push(data.avgStepNumber.toFixed(2));

            // 全天
            xDataList[3].push(data.avgTotalAmount.toFixed(2));
            xDataList[4].push(data.avgTotalStepNumber.toFixed(2));
          })

          this.initMutiLineChart(this.$refs.lineChart5, '月平均各项运动对比统计', categorys, xDataList);
        }
      })
    },
    student() {
      // 查询运动数据
      const params = {
        semesterId: this.searchData.semesterId,
        studentId: this.searchData.studentId,
        startDate: this.searchData.startDate,
        endDate: this.searchData.endDate
      }
      getAction(this.url.stuList, params).then(res => {
        if(res.success) {
          this.allList = res.result;
          
          //全园月平均
          var categorys = [];
          var xData1 = [];
          var xData2 = [];
          var xDataTime1 = [];

          var xData3 = [];
          var xData4 = [];
          var xDataTime2 = [];

          const daysColums = this.dataForm.daysColums;
          for(let rowIndex = 0; rowIndex < daysColums.length; rowIndex++){
            const rowString = daysColums[rowIndex].toString();
            categorys.push(rowString);
            const dayData = this.allList.find(item => item.statisticalDate == rowString);
            if (dayData){
              //全天
              xData1.push(dayData.totalAmount.toFixed(2));
              xData2.push(dayData.totalStepNumber.toFixed(2));
              xDataTime1.push(dayData.totalDuration.toFixed(2));

              //户外
              xData3.push(dayData.amount.toFixed(2));
              xData4.push(dayData.stepNumber.toFixed(2));
              xDataTime2.push(dayData.duration.toFixed(2));
            } else {
              xData1.push(0);
              xData2.push(0);
              xDataTime1.push(0);

              xData3.push(0);
              xData4.push(0);
              xDataTime2.push(0);
            }
          }
          //全天
          this.initDoubleLineChart(this.$refs.lineChart1, '当月每天全天运动量/步数统计', categorys, xData1, xData2); 
          this.initLineChart(this.$refs.lineChart2, '当月每天全天运动时长统计', categorys, xDataTime1);

          //户外
          this.initDoubleLineChart(this.$refs.lineChart3, '当月每天户外运动量/步数统计', categorys, xData3, xData4); 
          this.initLineChart(this.$refs.lineChart4, '当月每天户外运动时长统计', categorys, xDataTime2);
        } else {
          this.$message.warning(res.message);
          this.loading = false;
        }
      })

      // 查询月的平均运动量
      const params2 = {
        byType: 'all',
        semesterId: this.searchData.semesterId,
        studentId: this.searchData.studentId,
        startDate: this.searchData.startDate,
        endDate: this.searchData.endDate
      }
      getAction(this.url.stuList, params2).then(res => {
        if(res.success) {
          //全园月平均
          var categorys = ['运动量', '步数', '运动时长(分钟)'];
          var xDataList = [
            [],[]
          ];
          res.result.forEach(data => {
            // 全天
            xDataList[0].push(data.avgTotalAmount.toFixed(2));
            xDataList[0].push(data.avgTotalStepNumber.toFixed(2));
            xDataList[0].push(data.avgTotalDuration.toFixed(2));

            // 户外
            xDataList[1].push(data.avgAmount.toFixed(2));
            xDataList[1].push(data.avgStepNumber.toFixed(2));
            xDataList[1].push(data.avgDuration.toFixed(2));
          })

          this.initMutiBarChart(this.$refs.lineChart5, '月平均各项运动对比统计', categorys, xDataList);
        } else {
          this.$message.warning(res.message);
          this.loading = false;
        }
      })
    },
    initDoubleLineChart(el, title, categorys, xData1, xData2) {
      var myChartSports;
      if(this.$echarts.getInstanceByDom(el)) {
        myChartSports = this.$echarts.getInstanceByDom(el)
      }
      else{
        myChartSports = this.$echarts.init(el)
      }
      myChartSports.clear() //清空画布数据

      var legendTitle = ['运动量', '步数'];
      // option
      let optionSports = {
        backgroundColor: '#fff',
        title : {
          show:true,//显示策略，默认值true,可选为：true（显示） | false（隐藏）
          text: this.monthName + ' ' + this.className + title,//主标题文本，'\n'指定换行
          x:'center',//水平安放位置，默认为'left'，可选为：'center' | 'left' | 'right' | {number}（x坐标，单位px）
	        y:'top',//垂直安放位置，默认为top，可选为：'top' | 'bottom' | 'center' | {number}（y坐标，单位px）
        },
        tooltip: {
          borderColor: 'transparent',
          trigger: 'axis',
          backgroundColor: 'rgba(0,0,0,0.5)',
          axisPointer: {
            type: 'shadow',
            label: {
              show: true,
              backgroundColor: '#333'
            }
          },
          textStyle: {
            align: 'left',
            color: '#fff',
            fontSize: '12'
          }
        },
        legend: {
          data: legendTitle,
          textStyle: {
            color: '#ccc'
          },
          // orient: 'vertical', //垂直显示 
          // y: 'top', //延Y轴居中 
          // x: 'right', //居右显示
          right: '18%'
        },
        grid: {
          left: '10%',
          top: '15%',
          right: '10%',
          bottom: '10%'
        },
        xAxis: {
          data: categorys,
          axisLine: {
            lineStyle: {
              color: '#666'
            }
          }
        },
        yAxis: [
          {
            name: legendTitle[0],
            splitLine: {
              show: false
            },
            axisLine: {
              show: true,
              lineStyle: {
                color: '#999'
              }
            },
            nameTextStyle: {
              color: '#999'
            },
            splitArea: {
              show: false
            }
          },
          {
            name: legendTitle[1],
            splitLine: {
              show: false
            },
            axisLine: {
              show: true,
              lineStyle: {
                color: '#999'
              }
            },
            nameTextStyle: {
              color: '#999'
            },
            splitArea: {
              show: false
            }
          },
        ],
        series: [
          {
            name: legendTitle[0],
            type: 'line',
            smooth: true,
            showAllSymbol: true,
            symbol: 'emptyCircle',
            symbolSize: 8,
            itemStyle: {
              normal: {
                color: '#0BA6E3',
                label : {
                  show: true // 显示数据
                },
              }
            },
            data: xData1
          },
          {
            name: legendTitle[1],
            type: 'bar',
            barWidth: 10,
            yAxisIndex: 1,
            itemStyle: {
              normal: {
                barBorderRadius: [5,5,0,0],
                color: this.$echarts.graphic.LinearGradient(0, 0, 0, 1, [
                  {
                    offset: 0,
                    color: this.color[0]
                  },
                  {
                    offset: 1,
                    color: this.color[1]
                  }
                ]),
                label : {
                  show: true // 显示数据
                },
              }
            },
            data: xData2
          },
        ]
      }

      myChartSports.setOption(optionSports);
      setTimeout(() => {
        this.handleEmit()
      }, 3000);
      window.addEventListener("resize", ()=>{
        myChartSports.resize();
      })
    },
    initLineChart(el, title, categorys, xData) {
      var myChartSports;
      if(this.$echarts.getInstanceByDom(el)) {
        myChartSports = this.$echarts.getInstanceByDom(el)
      }
      else{
        myChartSports = this.$echarts.init(el)
      }
      myChartSports.clear() //清空画布数据

      const legendTitle = ['运动时长(分钟)'];
      var optionChart = {
        title : {
          show:true,//显示策略，默认值true,可选为：true（显示） | false（隐藏）
          text: this.monthName + ' ' + this.className + title,//主标题文本，'\n'指定换行
          x:'center',//水平安放位置，默认为'left'，可选为：'center' | 'left' | 'right' | {number}（x坐标，单位px）
	        y:'top',//垂直安放位置，默认为top，可选为：'top' | 'bottom' | 'center' | {number}（y坐标，单位px）
        },
        tooltip: {
          borderColor: 'transparent',
          trigger: 'axis',
          backgroundColor: 'rgba(0,0,0,0.5)',
          axisPointer: {
            type: 'shadow',
            label: {
              show: true,
              backgroundColor: '#333'
            }
          },
          textStyle: {
            align: 'left',
            color: '#fff',
            fontSize: '12'
          }
        },
        legend: {
          data: legendTitle,
          textStyle: {
            color: '#ccc'
          },
          // orient: 'vertical', //垂直显示 
          // y: 'top', //延Y轴居中 
          // x: 'right', //居右显示
          right: '18%'
        },
        xAxis: {
          type: 'category',
          data: categorys
        },
        yAxis: {
          type: 'value'
        },
        series: [
          {
            name: legendTitle[0],
            data: xData,
            type: 'line',
            itemStyle: {
              normal: {
                color: '#0BA6E3',
                label : {
                  show: true // 显示数据
                },
              }
            },
            smooth: true
          }
        ]
      };

      myChartSports.setOption(optionChart);
      setTimeout(() => {
        this.handleEmit()
      }, 3000);
      window.addEventListener("resize", ()=>{
        myChartSports.resize();
      })
    },
    initMutiLineChart(el, title, categorys, xDataList) {
      var myChartSports;
      if(this.$echarts.getInstanceByDom(el)) {
        myChartSports = this.$echarts.getInstanceByDom(el)
      }
      else{
        myChartSports = this.$echarts.init(el)
      }
      myChartSports.clear() //清空画布数据

      var legendTitle = ['户外运动时长', '户外运动量', '户外步数', '总运动量', '总步数'];
      // option
      let optionSports = {
        backgroundColor: '#fff',
        title : {
          show:true,//显示策略，默认值true,可选为：true（显示） | false（隐藏）
          text: this.monthName + ' ' + this.className + title,//主标题文本，'\n'指定换行
          x:'center',//水平安放位置，默认为'left'，可选为：'center' | 'left' | 'right' | {number}（x坐标，单位px）
	        y:'top',//垂直安放位置，默认为top，可选为：'top' | 'bottom' | 'center' | {number}（y坐标，单位px）
        },
        tooltip: {
          borderColor: 'transparent',
          trigger: 'axis',
          backgroundColor: 'rgba(0,0,0,0.5)',
          axisPointer: {
            type: 'shadow',
            label: {
              show: true,
              backgroundColor: '#333'
            }
          },
          textStyle: {
            align: 'left',
            color: '#fff',
            fontSize: '12'
          }
        },
        legend: {
          data: legendTitle,
          textStyle: {
            color: '#ccc'
          },
          // orient: 'vertical', //垂直显示 
          y: 'top', //延Y轴居中 
          x: 'right', //居右显示
          right: '20%'
        },
        grid: {
          left: '10%',
          top: '15%',
          right: '10%',
          bottom: '10%'
        },
        xAxis: {
          data: categorys,
          axisLine: {
            lineStyle: {
              color: '#666'
            }
          }
        },
        yAxis: [
          {
            name: '运动量',
            position: 'left',
            splitLine: {
              show: false
            },
            axisLine: {
              show: true,
              lineStyle: {
                color: '#999'
              }
            },
            nameTextStyle: {
              color: '#999'
            },
            splitArea: {
              show: false
            }
          },
          {
            name: '步数',
            position: 'right',
            splitLine: {
              show: false
            },
            axisLine: {
              show: true,
              lineStyle: {
                color: '#999'
              }
            },
            nameTextStyle: {
              color: '#999'
            },
            splitArea: {
              show: false
            }
          },
          {
            name: '时长(分钟)',
            min: 0,
            max: 220,
            position: 'right',
            offset: 80, // y轴位置的偏移量
            splitLine: {
              show: false
            },
            axisLine: {
              show: true,
              lineStyle: {
                color: '#999'
              }
            },
            nameTextStyle: {
              color: '#999'
            },
            splitArea: {
              show: false
            }
          },
        ],
        series: [
          {
            name: legendTitle[0],
            type: 'line',
            smooth: true,
            showAllSymbol: true,
            symbol: 'emptyCircle',
            symbolSize: 8,
            yAxisIndex: 2,
            itemStyle: {
              normal: {
                color: '#0BA6E3',
                label : {
                  show: true // 显示数据
                },
              }
            },
            data: xDataList[0]
          },
          {
            name: legendTitle[1],
            type: 'line',
            smooth: true,
            showAllSymbol: true,
            symbol: 'emptyCircle',
            symbolSize: 8,
            yAxisIndex: 0,
            itemStyle: {
              normal: {
                color: '#07D6E2',
                label : {
                  show: true // 显示数据
                },
              }
            },
            data: xDataList[1]
          },
          {
            name: legendTitle[2],
            type: 'line',
            smooth: true,
            showAllSymbol: true,
            symbol: 'emptyCircle',
            symbolSize: 8,
            yAxisIndex: 1,
            itemStyle: {
              normal: {
                color: '#EBB310',
                label : {
                  show: true // 显示数据
                },
              }
            },
            data: xDataList[2]
          },
          {
            name: legendTitle[3],
            type: 'line',
            smooth: true,
            showAllSymbol: true,
            symbol: 'emptyCircle',
            symbolSize: 8,
            yAxisIndex: 0,
            itemStyle: {
              normal: {
                color: '#08A618',
                label : {
                  show: true // 显示数据
                },
              }
            },
            data: xDataList[3]
          },
          {
            name: legendTitle[4],
            type: 'line',
            smooth: true,
            showAllSymbol: true,
            symbol: 'emptyCircle',
            symbolSize: 8,
            yAxisIndex: 1,
            itemStyle: {
              normal: {
                color: '#7CF859',
                label : {
                  show: true // 显示数据
                },
              }
            },
            data: xDataList[4]
          },
        ]
      }

      myChartSports.setOption(optionSports);
      setTimeout(() => {
        this.handleEmit()
      }, 3000);
      window.addEventListener("resize", ()=>{
        myChartSports.resize();
      })
    },
    initMutiBarChart(el, title, categorys, xDataList) {
      var myChartSports;
      if(this.$echarts.getInstanceByDom(el)) {
        myChartSports = this.$echarts.getInstanceByDom(el)
      }
      else{
        myChartSports = this.$echarts.init(el)
      }
      myChartSports.clear() //清空画布数据

      var legendTitle = ['全天', '户外'];
      // option
      let optionSports = {
        backgroundColor: '#fff',
        title : {
          show:true,//显示策略，默认值true,可选为：true（显示） | false（隐藏）
          text: this.monthName + ' ' + this.className + title,//主标题文本，'\n'指定换行
          x:'center',//水平安放位置，默认为'left'，可选为：'center' | 'left' | 'right' | {number}（x坐标，单位px）
	        y:'top',//垂直安放位置，默认为top，可选为：'top' | 'bottom' | 'center' | {number}（y坐标，单位px）
        },
        tooltip: {
          borderColor: 'transparent',
          trigger: 'axis',
          backgroundColor: 'rgba(0,0,0,0.5)',
          axisPointer: {
            type: 'shadow',
            label: {
              show: true,
              backgroundColor: '#333'
            }
          },
          textStyle: {
            align: 'left',
            color: '#fff',
            fontSize: '12'
          }
        },
        legend: {
          data: legendTitle,
          textStyle: {
            color: '#ccc'
          },
          // orient: 'vertical', //垂直显示 
          y: 'top', //延Y轴居中 
          x: 'right', //居右显示
          right: '20%'
        },
        grid: {
          left: '10%',
          top: '15%',
          right: '10%',
          bottom: '10%'
        },
        xAxis: {
          data: categorys,
          axisLine: {
            lineStyle: {
              color: '#666'
            }
          }
        },
        yAxis: [
          {
            name: '运动量',
            position: 'left',
            splitLine: {
              show: false
            },
            axisLine: {
              show: true,
              lineStyle: {
                color: '#999'
              }
            },
            nameTextStyle: {
              color: '#999'
            },
            splitArea: {
              show: false
            }
          },
          {
            name: '步数',
            position: 'right',
            splitLine: {
              show: false
            },
            axisLine: {
              show: true,
              lineStyle: {
                color: '#999'
              }
            },
            nameTextStyle: {
              color: '#999'
            },
            splitArea: {
              show: false
            }
          },
          {
            name: '时长(分钟)',
            min: 0,
            max: 220,
            position: 'right',
            offset: 80, // y轴位置的偏移量
            splitLine: {
              show: false
            },
            axisLine: {
              show: true,
              lineStyle: {
                color: '#999'
              }
            },
            nameTextStyle: {
              color: '#999'
            },
            splitArea: {
              show: false
            }
          },
        ],
        series: [
          {
            name: legendTitle[0],
            type: 'bar',
            barWidth: 10,
            barGap: '100%',
            yAxisIndex: 0,
            itemStyle: {
              normal: {
                barBorderRadius: [5,5,0,0],
                color: '#0BA6E3',
                label : {
                  show: true // 显示数据
                },
              }
            },
            data: xDataList[0]
          },
          {
            name: legendTitle[1],
            type: 'bar',
            barWidth: 10,
            yAxisIndex: 1,
            itemStyle: {
              normal: {
                barBorderRadius: [5,5,0,0],
                color: '#EBB310',
                label : {
                  show: true // 显示数据
                },
              }
            },
            data: xDataList[1]
          },
        ]
      }

      myChartSports.setOption(optionSports);
      setTimeout(() => {
        this.handleEmit()
      }, 3000);
      window.addEventListener("resize", ()=>{
        myChartSports.resize();
      })
    },
    handleEmit(){
      this.numList.push(true);
      if (this.numList.length == 5) {
        this.$emit("ok")
      }
    }
  }
}
</script>
<style scoped lang="less">
</style>